import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:ls_work/a_elder/page/bed_change_history_page.dart';
import 'package:ls_work/a_yyt/home_router.dart';
import 'package:ls_work/a_yyt/page/home_care_report_page.dart';
import 'package:ls_work/a_yyt/page/medical_package_page.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:ls_work/doctor_patrol/ui/doctor_patrol_record_page.dart';
import 'package:ls_work/init_page/webview_page.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/model/customer_info_model.dart';
import 'package:ls_work/model/food/printer_model.dart';
import 'package:ls_work/model/sys_info_model.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/food/order_model_list_data.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/operational_statistics/ui/operational_statistics_page.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/routers/fluro_navigator.dart';
import 'package:ls_work/self_medicine/ui/self_medicine_library_page.dart';
import 'package:ls_work/ui/activity/activity_record_page.dart';
import 'package:ls_work/ui/device/device_repair_page.dart';
import 'package:ls_work/ui/food_sample/food_sample_list_page.dart';
import 'package:ls_work/ui/hand_over/new_hand_over_home_page.dart';
import 'package:ls_work/ui/leave/leave_record_page.dart';
import 'package:ls_work/ui/meal/meal_record_view_page.dart';
import 'package:ls_work/ui/medical/medical_record_page.dart';
import 'package:ls_work/ui/medicine/medical_advice_manage_page.dart';
import 'package:ls_work/ui/medicine/medicine_handover/medicine_handover_list_page.dart';
import 'package:ls_work/ui/medicine/medicine_lack_list_page.dart';
import 'package:ls_work/ui/medicine/put_medicine/put_medicine_list_page.dart';
import 'package:ls_work/ui/medicine/receive_medicine/receive_medicine_list_page.dart';
import 'package:ls_work/ui/medicine/take_medicine/take_medicien_list_page.dart';
import 'package:ls_work/ui/medicine/treatment_sheet_list_page.dart';
import 'package:ls_work/ui/new_health/new_health_sign_page.dart';
import 'package:ls_work/ui/patrol/patrol_detail_page.dart';
import 'package:ls_work/ui/patrol/patrol_list_home_page.dart';
import 'package:ls_work/ui/scheduling/work_scheduling_info_page.dart';
import 'package:ls_work/ui/select_building_floor_page.dart';
import 'package:ls_work/ui/select_old_page.dart';
import 'package:ls_work/ui/service_order/service_order_home_page.dart';
import 'package:ls_work/ui/service_order/simple_service_order_list_page.dart';
import 'package:ls_work/ui/set_url_page.dart';
import 'package:ls_work/ui/visitor_check/visitor_check_list_page.dart';
import 'package:ls_work/util/event_bus.dart' as e;
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/util/notifycation_utils.dart';
import 'package:ls_work/util/speak_text_service.dart';
import 'package:ls_work/util/utils.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:nfc_manager/platform_tags.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:saas_warning_package/saas_warning_package.dart';
import 'package:visitor_scan_package/net/account/axun_user.dart';
import 'package:visitor_scan_package/ui/home_page.dart';

import '../a_yyt/page/policy_remine_page.dart';
import '../abnormal_event_center/ui/abnormal_event_center_page.dart';
import '../bad_event/ui/bad_event_list_page.dart';
import '../doctor_advice/doctor_advice_list_page.dart';
import '../emergency_event/ui/emergency_event_record_page.dart';
import '../login/page/user_manager.dart';
import '../login/user_permission_data.dart';
import '../model/decode_qrcode_model.dart';
import '../model/patrol/patrol_task_model.dart';
import '../model/service_order/service_order_model.dart';
import '../net/response/user_info_data.dart';
import '../net/response/work_menu_data.dart';
import '../permission/permission_request.dart';
import '../print/sunmi_print_utils.dart';
import '../service/sos_warning_service.dart';
import '../ui/address_book/address_book_list_page.dart';
import '../ui/device/device_repair_submit_page.dart';
import '../ui/elder_detail_info_page.dart';
import '../ui/entry_record/entry_record_home_page.dart';
import '../ui/event_manage/event_manage_list_page.dart';
import '../ui/food/select_order_type_page.dart';
import '../ui/iot/iot_list_page.dart';
import '../ui/medicine_advice/medicine_advice_list_page.dart';
import '../ui/meter_reading/meter_reading_home_page.dart';
import '../ui/new_actvity/activity_recommend_list_page.dart';
import '../ui/patrol/offline_patrol_detail_page.dart';
import '../ui/patrol/offline_task_list_page.dart';
import '../ui/send_order/send_order_list_page.dart';
import '../ui/service_execute/service_extcute_statistics_home_page.dart';
import '../ui/use_request/use_request_record_page.dart';
import '../ui/waring/set_warning_info_page.dart';
import '../update_app_utils/app_update_utils.dart';
import '../update_app_utils/update_dialog.dart';
import '../util/location_utils.dart';
import '../util/push_utils.dart';
import '../util/request_url_utils.dart';

class NewYytViewModel extends BaseViewModel {
  NewYytViewModel(BuildContext context) : super(context);

  DecodeQrcodeModel model = new DecodeQrcodeModel();
  var serviceModel = ServiceOrderModel();
  var patrolModel = PatrolTaskModel();
  var sysModel = SysInfoModel();
  var localPatrolRecordNum = 0;

  var customerModel = CustomerInfoModel();
  var isOnTop = true;

  static UserInfoData? userInfo;
  static bool canSendOrder = false;

  AppUpdateUtil? utils;

  Future<void> getUserInfo() async {
    try {
      var data = await PostRequest.userInfo();
      var bean = ResponseBean.fromJson(data);
      if ("0" == bean.code) {
        var info = UserInfoData.fromJson(bean.data);
        userInfo = info;
      }
    } catch (e) {}
  }

  var inScan = false;

  Future<void> getLocalPatrolNum() async {
    if (!GlobalConfigs.useOfflinePatrol) {
      return;
    }
    var list = await patrolModel.getLocalRecord();
    localPatrolRecordNum = list.length;
    notifyListeners();
  }

  Future<void> _scanResult(String code, {bool isNfc = false}) async {
    if (inScan) {
      return;
    }
    inScan = true;
    if (GlobalConfigs.useOfflinePatrol) {
      showLoadingDialog(msg: '正在解析...');
      var resultMap = await Utils.decodeQrcode(code);
      print("2222");
      hideDialog();
      if (resultMap != null && resultMap['type'] == '11') {
        var taskList = await patrolModel.getLocalTask();
        if (taskList.isEmpty) {
          showToast("请现在安全巡防模块中获取今日任务");
          return;
        }
        var localTaskPoint = await patrolModel.searchTaskPointByQrcode(code);
        if (localTaskPoint != null && localTaskPoint.isNotEmpty) {
          if (OfflinePatrolDetailPage.isOnTop) {
            return;
          }
          Go().push(OfflinePatrolDetailPage(code));
        } else {
          showToast("当前时间无可执行任务");
        }
        inScan = false;
        return;
      }
    }
    showLoadingDialog();
    try {
      var data = await model.decoed(code);
      hideDialog();
      switch (data.typeCode) {
        case 1:
          // Go().push(ElderInfoPage(
          //   customerId: data.id!.toInt(),
          // ));
          Go().push(ElderDetailInfoPage(
            customerId: data.id!,
          ));
          isOnTop = false;
          break;
        case 2:
          break;
        case 3:
          break;

        case 4:
          Go().push(BedChangeHistoryPage(data.id!));
          isOnTop = false;
          break;
        case 11:
          if (isNfc && GlobalConfigs.submitDirectNfc) {
            _submitPatrolByNfc(code);
          } else {
            Go().push(PatrolDetailPage(code));
            isOnTop = false;
          }
          break;
        case 12:
          Go().push(DeviceRepairSubmitPage(
            content: code,
          ));
          isOnTop = false;
          break;
      }
      inScan = false;
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
      inScan = false;
    }
  }

  ///扫码跳转
  Future<void> scanCode() async {
    var result = await Utils.scan();
    if (!result.isNullOrEmpty()) {
      if (result.contains("192.168.")) {
        Go().push(SetUrlPage(result));
      } else if (Utils.isCloudPrinter(result)) {
        bindCloudPrinter(result);
      } else {
        _scanResult(result);
      }
    }
  }

  var printerModel = PrinterModel();

  void bindCloudPrinter(String snCode) {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text("绑定打印机"),
            content: CommonText('是否绑定该打印机,\nsn:${snCode}',
                textAlign: TextAlign.center),
            actions: [
              TextButton(
                  onPressed: () {
                    Go().pop();
                  },
                  child: CommonText('取消', textColor: Colors.grey)),
              TextButton(
                  onPressed: () {
                    Go().pop();
                    _bind(snCode);
                  },
                  child: CommonText('确定', textColor: Colours.app_main)),
            ],
          );
        });
  }

  Future<void> _bind(String code) async {
    showLoadingDialog(msg: '提交中...');
    try {
      await printerModel.bindPrinter(code);
      hideDialog();
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  Map<dynamic, dynamic>? toMap(String result) {
    var data = result.split("?");
    if (data.length <= 1) {
      return null;
    }
    var query = data[1].split("&".toReg());
    var map = {};
    query.forEach((element) {
      var data = element.split("=");
      map[data[0]] = data[1];
    });
    return map;
  }

  Widget contentWidget() {
    return Column(
      children: UserPermissionData.menuList.map((e) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  width: 4,
                  height: 14,
                  color: Color(0xFF2DA0D1),
                  margin: EdgeInsets.only(top: 3),
                ),
                SizedBox(
                  width: 8,
                ),
                Text(
                  e.title ?? "",
                  style: TextStyle(
                      fontWeight: FontWeight.w500,
                      fontSize: 18,
                      color: Color(0xff333333)),
                )
              ],
            ).addToContainer(
                margin: EdgeInsets.only(left: 16, right: 16, bottom: 23)),
            functionWidget(e)
          ],
        ).addToContainer(
            color: Colors.white, padding: EdgeInsets.only(top: 14, bottom: 18));
      }).toList(),
    );
  }

  Widget functionWidget(WorkMenuData data) {
    var siz = MediaQuery.of(context).size;
    return GridView.builder(
      shrinkWrap: true,
      padding: EdgeInsets.symmetric(horizontal: 16),
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: siz.width < siz.height ? 4 : 7,
          mainAxisSpacing: 24,
          childAspectRatio: 1.2),
      itemBuilder: (context, index) {
        var item = data.subMenus![index];
        return Stack(
          children: [
            Column(
              children: [
                ImageLoad(
                  formatImage(
                      UserPermissionData.getFunImage(item.moduleName ?? ""),
                      parentPath: "assets"),
                  isAsset: true,
                  width: 44,
                  height: 44,
                ),
                Container(
                  height: 6,
                ),
                CommonText(item.title,
                    textColor: Color(0xff333333), fontWeight: FontWeight.w500)
              ],
            ),
            if ((item.count ?? 0) > 0)
              Text(
                "${item.count}",
                style: TextStyle(color: Colors.white),
              )
                  .addToContainer(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: Colors.red, borderRadius: 20.borderRadius),
                      constraints: BoxConstraints(minWidth: 20, minHeight: 20))
                  .setLocation(right: 30)
          ],
        ).onTap(() async {
          isOnTop = false;
          await openToFunction(item);
          isOnTop = true;
          getHomeCount();
        });
      },
      itemCount: (data.subMenus ?? []).length,
    );
  }

  Future<void> openToFunction(SubMenusListBean item) async {
    switch (item.moduleName) {
      case UserPermissionData.careRecord:
        await Go().push(HomeCareReportPage());
        break;
      case UserPermissionData.healthSign:
        // AppNavigator.push(context, HealthHomePage());
        await Go().push(NewHealthSignPage());
        break;
      case UserPermissionData.activitySign:
        await Go().push(ActivityRecordPage());
        break;
      case UserPermissionData.leaveSign:
        await Go().push(LeaveRecordPage());
        break;
      case UserPermissionData.mealSign:
        await Go().push(MealRecordPage());
        break;
      case UserPermissionData.medicalSign:
        await Go().push(MedicalRecordPage());
        break;
      case UserPermissionData.handOver:
        await Go().push(NewHandOverHomePage());
        // Go().push(HomeHandoverPage());
        break;
      case UserPermissionData.healthCheck:
        // if(BuildConfig.isDebug){
        //   Go().push(Pc300TestPage());
        //   return;
        // }
        // if (await PermissionRequest.isLackPermission(
        //         Permission.bluetoothScan) &&
        //     Platform.isAndroid) {
        //   showApplyDialog(
        //       context: context,
        //       onSubmit: () async {
        //         var result = await PermissionRequest.requestPermissions(
        //             [Permission.bluetoothScan, Permission.bluetoothConnect]);
        //         await Go().push(MedicalPackagePage());
        //       },
        //       message: "连接健康设备需要获取蓝牙权限");
        // } else {
        //
        // }
        Permission.bluetoothScan.checkRequestPermission(context, onSuccess: () {
          // Permission.locationWhenInUse.checkRequestPermission(context,
          //     onSuccess: () async {
            Permission.bluetoothConnect.checkRequestPermission(context,
                onSuccess: () async {
              await Go().push(MedicalPackagePage());
            }, msg: '连接体检包需要获取蓝牙连接权限');
          // }, msg: '连接健康设备需要获取定位权限');
        }, msg: '扫描体检包需要获取蓝牙权限');

        break;
      case UserPermissionData.serviceOrder:
        await Go().push(ServiceOrderHomePage());
        break;
      case UserPermissionData.safePatrol:
        // Go().push(PatrolListHomePage());
        if (GlobalConfigs.useOfflinePatrol) {
          await Go().push(OfficeTaskListPage());
        } else {
          await Go().push(PatrolListHomePage());
        }

        break;
      case UserPermissionData.equipmentRepair:
        await Go().push(DeviceRepairPage());
        break;
      case UserPermissionData.nurseCare:
        await Go().push(ServiceExecuteStatisticsHomePage());
        break;
      case UserPermissionData.nurseCareNew:
        await Go().push(ServiceExecuteStatisticsHomePage(
          useNew: true,
        ));
        break;
      case UserPermissionData.orderMeal:
        await Go().push(SelectOrderTypePage());
        break;
      case UserPermissionData.visitorCheck:
        await Go().push(ScanVisitorHomePage(
          showLogout: false,
        ));
        break;
      case UserPermissionData.warningNotice:
        await Go().push(PolicyReminePage());
        break;
      case UserPermissionData.visitorAudit:
        await Go().push(VisitorCheckListPage());
        break;
      case UserPermissionData.sendServiceOrder:
        await Go().push(SendOrderListPage());
        break;
      case UserPermissionData.foodSample:
        await Go().push(FoodSampleListPage());
        break;
      case UserPermissionData.meterReading:
        await Go().push(SelectBuildingFloorPage(
          callback: (buildingId, floorId, buildingName, floorName) {
            Go().push(MeterReadingHomePage(
              buildingId: buildingId,
              floorId: floorId,
              buildingName: buildingName,
              floorName: floorName,
            ));
          },
        ));
        break;
      case UserPermissionData.simpleServiceOrder:
        await Go().push(SimpleServiceOrderListPage());
        break;
      case UserPermissionData.smartEquipment:
        await Go().push(IotListPage());
        break;

      case UserPermissionData.schedulingPlan:
        await Go().push(WorkSchedulingInfoPage());
        break;
      case UserPermissionData.signInActivity:
        await Go().push(ActivityRecommendListPage());
        break;
      case UserPermissionData.approval:
        var approvalUrl =
            "${HttpApi.approveUrl}bpm-dynamic-list?token=${UserManager.cookieStr.replaceAll("JSESSIONID=", "")}";
        print(approvalUrl);
        await Go().push(WebViewPage(title: "审批", url: approvalUrl));
        break;
      case UserPermissionData.useRequest:
        await Go().push(UseRequestRecordPage());
        break;
      case UserPermissionData.addressBook:
        await Go().push(AddressBookListPage());
        // await Go().push(HomeAddressBookPage());
        break;
      case UserPermissionData.eventManage:
        await Go().push(EventManageListPage());
        break;
      case UserPermissionData.medicalAdvice:
        await Go().push(MedicalAdviceManagePage());
        break;
      case UserPermissionData.treatmentSheet:
        await Go().push(TreatmentSheetListPage());
        break;
      case UserPermissionData.medicineLack:
        await Go().push(MedicineLackListPage());
        break;
      case UserPermissionData.receiveMedicine:
        await Go().push(ReceiveMedicineListPage());
        break;
      case UserPermissionData.medicineHandover:
        await Go().push(MedicineHandoverListPage());
        break;
      case UserPermissionData.putMedicine:
        await Go().push(PutMedicineListPage());
        break;
      case UserPermissionData.takeMedicine:
        await Go().push(TakeMedicineListPage());
        break;
      case UserPermissionData.entryRecord:
        await Go().push(EntryRecordHomePage());
        break;
      case UserPermissionData.medicineAdviceCheck:
        await Go().push(MedicineAdviceListPage());
        break;
      case UserPermissionData.badEvent:
        await Go().push(BadEventListPage());
        break;
      case UserPermissionData.abnormalEvent:
        await Go().push(AbnormalEventCenterPage());
        break;
      case UserPermissionData.operationalStatistics:
        await Go().push(OperationalStatisticsPage());
        break;
      case UserPermissionData.emergencyEvent:
        await Go().push(EmergencyEventRecordPage());
        break;
      case UserPermissionData.doctorPatrol:
        await Go().push(DoctorPatrolRecordPage());
        break;
      case UserPermissionData.medicineLibrarySearch:
        Go().push(SelectOldPage((old) async {
          await Go().push(SelfMedicineLibraryPage(
            elderName: old.name,
            sexName: old.sexName,
            roomNo: old.roomNo,
            customerId: old.id,
          ));
        }));
        break;
      case UserPermissionData.doctorAdviceSign:
        await Go().push(DoctorAdviceListPage());
        break;
    }
  }

  Future<void> getOrderModel() async {
    showLoadingDialog();
    try {
      var data = await PostRequest.getOrderModel(1, 20);
      hideDialog();
      if ("0" == data['code'].toString()) {
        var bean = ResponseBean.fromJson(data);
        var list = ((bean.data['rows'] as List?) ?? [])
            .map((e) => OrderModelListData.fromJson(e))
            .toList();
        showBottomSelectSheet<PickerDataWithIdModel>(context,
            items: list
                .map((e) => PickerDataWithIdModel(
                    pickName: e.name, pickId: e.orderType.toString()))
                .toList(),
            onSelect: (item) {});
      } else {
        showToast(data['msg']);
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  var showHealth = false;

  @override
  void onCreated() {
    super.onCreated();
    showHealth = SpUtil.getBool("showHealth", defValue: false) ?? false;

    notifyListeners();

    initBase();
  }

  Future<void> setBranch() async {
    try {
      await HttpGo.instance.postData("${HttpApi.baseUrl}setCurBranch",
          data: {"branchId": RequestUrlUtils.branchId},
          options: Options(contentType: Headers.formUrlEncodedContentType));
    } catch (e) {}
  }

  Future<void> initBase() async {
    await GlobalConfigs.init();
    //
    if (Platform.isAndroid) {
      SunmiPrinterUtils.initSunmiPrinter();
    }
    HttpUtil.instance.getDio();
    UserManager.instance.init();
    await setBranch();
    //
    if (Platform.isAndroid) {
      Permission.notification.checkRequestPermission(context, onSuccess: () {
        if (GlobalConfigs.receiveSos) {
          _setSosService();
        }
        NotifycationUtils.instance.init();
        PushUtils.initPush(context);
      }, msg: '消息接收需要申请您的通知权限', showAgain: false);
      // _initScanner();
    } else {
      initIosSos();
    }
    initNfc();

    getSysInfo();
    getUserInfo();
    _initSendOrderPermission();
    getHomeCount();
    _updateApp();
    receiveSosMsg();
    getLocalPatrolNum();

    LocationConfig.instance.preInit();
    // checkWarningSetting();
  }

  Future<void> _setSosService() async {
    if (await SosWarningService.instance.startService()) {
      Future.delayed(Duration(milliseconds: 1000), () {
        print("startService");
        SosWarningService.instance.sendUrlMsg(
            HttpApi.baseUrl, RequestUrlUtils.branchId,
            accountName: UserManager.userName ?? "admin111");
        SosWarningService.instance.sendEnableReceive(GlobalConfigs.receiveSos);
      });
      await SpUtil.putString("url", HttpApi.baseUrl);
      await SpUtil.putString("branchId", RequestUrlUtils.branchId);
    }
  }

  void _updateApp() {
    if (Platform.isAndroid) {
      utils = new AppUpdateUtil();
      Timer(const Duration(milliseconds: 1000), () {
        utils?.getVersion().then((value) {
          if (value != null) {
            var force = value['isForce'] ?? 0;
            _showUpdateDialog(value, force: force == 1);
          }
        });
      });
    }
  }

  void _showUpdateDialog(Map netMap, {bool force = false}) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => UpdateDialog(
        netMap: netMap,
        force: force,
      ),
    );
  }

  Future<void> _initSendOrderPermission() async {
    canSendOrder = await serviceModel.canSendOrder();
  }

  bool nfcEnable = false;

  // void _initScanner() {
  // SunmiScanner.onBarcodeScanned().listen((event) {
  //   _scanResult(event);
  // });
  // }

  Future<void> getCustomerInfoByCard(String cardNumber) async {
    showLoadingDialog();
    try {
      var info = await customerModel.getCardAccount(physicalCardNo: cardNumber);
      hideDialog();
      Go().push(ElderDetailInfoPage(
        customerId: info.data?.human?.id,
      ));
    } catch (e) {
      showToast(e.toNetError());
      hideDialog();
    }
  }

  Future<void> initNfc() async {
    nfcEnable = await NfcManager.instance.isAvailable();
    if (!Platform.isAndroid) {
      return;
    }
    if (nfcEnable) {
      NfcManager.instance.startSession(
          onDiscovered: (NfcTag tag) async {
            ///ic卡读取物理卡号
            MifareClassic? ic = MifareClassic.from(tag);
            if (ic != null) {
              var idCard16 = ic.identifier
                  .toList()
                  .reversed
                  .map((e) => e.toRadixString(16).padLeft(2, '0'))
                  .join("")
                  .toUpperCase();
              var idCard = idCard16.toInteger(radix: 16).toString();
              if (isOnTop) {
                getCustomerInfoByCard(idCard);
              } else {
                sendMessage(SendMessageEvent(MessageConfig.NFC_READ_IC_CARD,
                    obj: idCard));
              }
            }

            Ndef? ndef = Ndef.from(tag);
            if (ndef != null) {
              if (ndef.cachedMessage?.records.isNotEmpty ?? false) {
                var payload = ndef.cachedMessage?.records[0].payload;
                var str = String.fromCharCodes(
                  payload!,
                  3,
                );
                if (isOnTop) {
                  _scanResult(str, isNfc: true);
                } else {
                  sendMessage(SendMessageEvent(MessageConfig.NFC_READ_MESSAGE,
                      obj: str));
                }
              }
            }
            // showToast(ndef.cachedMessage.records[0].);
            // print(jsonEncode(tag.data));
          },
          onError: (error) async {
            showToast(error.message);
          },
          alertMessage: "1111");
    } else {
      print("不支持nfc");
    }
  }

  void startNfc() {
    if (nfcEnable) {
      print("开始识别nfc");
      NfcManager.instance.startSession(
          onDiscovered: (NfcTag tag) async {
            Ndef? ndef = Ndef.from(tag);
            if (ndef?.cachedMessage?.records?.isNotEmpty ?? false) {
              var payload = ndef?.cachedMessage?.records[0].payload;
              // var languageLength = payload[0];
              // showToast(languageLength.toString());
              var str = String.fromCharCodes(
                payload!,
                3,
              );
              _scanResult(str);
            }
            print(jsonEncode(tag.data));
            NfcManager.instance.stopSession();
          },
          onError: (error) async {
            print(error);
          },
          alertMessage: "准备扫描，将标签贴近手机");
    } else {
      print("不支持nfc");
    }
  }

  @override
  void onDispose() {
    if (nfcEnable) {
      NfcManager.instance.stopSession();
    }
    // DataSocketUtils.instence.release();
    super.onDispose();
  }

  @override
  void onPause() {
    isOnTop = false;
    print("pause");
  }

  @override
  void onResume() {
    isOnTop = true;
    getHomeCount();
  }

  var inRelogin = false;

  Future<void> _relogin() async {
    if (inRelogin) {
      return;
    }
    inRelogin = true;

    var params = {
      "username": UserManager.account,
      "password": UserManager.pdd,
      "needMenu": true,
      "needAppMenu": true
    };
    showLoadingDialog(msg: "登录中。。。");
    try {
      var data = await HttpGo.instance.postData(HttpApi.login,
          data: params, options: PostRequest.urlencodedHeader);
      hideDialog();
      UserManager.instance.login(data['data']);
      e.eventBus.emit('relogin');
      UserPermissionData.saveMenus(data['data']['menus']);
      notifyListeners();
      inRelogin = false;
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
      inRelogin = false;
    }
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if (event.msgCode == MessageConfig.RESTART_NFC) {
      initNfc();
    }
    if (event.msgCode == MessageConfig.RELOGIN) {
      _relogin();
    }
    if (event.msgCode == 1) {
      if (isInWarning) {
        return;
      }
      var text = event.obj as String;
      showCupertinoDialog(
          context: context,
          builder: (context) {
            return CupertinoAlertDialog(
              title: Text(
                '报警提醒',
              ),
              content: Text(
                text,
                style: TextStyle(
                  fontSize: 16,
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                    NavigatorUtils.push(context, HomeRouter.medicalPolicyPage);
                  },
                  child: CommonText('前往处理'),
                )
              ],
            );
          });
    }

    if (event.msgCode == MessageConfig.ENABLE_BATCH) {
      getHomeCount();
    }

    if (event.msgCode == MessageConfig.REFRESH_LOCAL_PATROL) {
      getLocalPatrolNum();
    }
  }

  var count = 0;

  void clickToShowHealth() {
    count++;
    if (count == 5) {
      SpUtil.putBool("showHealth", true);
      showHealth = true;
      notifyListeners();
    }
  }

  Future<void> getHomeCount() async {
    try {
      var countData = await HttpGo.instance.getData(HttpApi.homeCount);
      var sosCount = countData['data']['alarmNum'];
      UserPermissionData.menuList.forEach((type) {
        type.subMenus?.forEach((element) {
          if (element.moduleName == UserPermissionData.warningNotice) {
            element.count = sosCount;
          }
        });
      });
      notifyListeners();
    } catch (e) {}
  }

  var dialogTag = <String>[];

  void initIosSos() {
    var canReceive = true;
    SaasWarningPackage.instance.initBranchId(RequestUrlUtils.branchId);
    SaasWarningPackage.instance
        .initUrl(HttpApi.baseUrl, account: AxunUser.userAccount ?? "");
    SaasWarningPackage.instance.connectSocket();
    SaasWarningPackage.instance.setReceiveListener(
        receiveWarningCall: (callInfo) async {
          if (canReceive) {
            SpeakTextService.speak(callInfo.speechMsg ?? "");
            if (isInWarning) {
              return;
            }
            if (dialogTag.isNotEmpty) {
              for (var item in dialogTag) {
                await SmartDialog.dismiss(tag: item);
              }
            }

            dialogTag.add(callInfo.id.toStringOrNull() ?? "");
            SmartDialog.show(
                builder: (_context) {
                  return Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                        height: 16,
                      ),
                      CommonText('报警提醒'),
                      SizedBox(
                        height: 16,
                      ),
                      CommonText(callInfo.msg, textAlign: TextAlign.center)
                          .addToContainer(
                              padding: EdgeInsets.symmetric(horizontal: 12)),
                      SizedBox(
                        height: 16,
                      ),
                      TextButton(
                          onPressed: () {
                            SmartDialog.dismiss(tag: callInfo.id.toString());
                            NavigatorUtils.push(
                                context, HomeRouter.medicalPolicyPage);
                          },
                          child: CommonText('前往处理'))
                    ],
                  ).addToContainer(
                      width: MediaQuery.of(_context).size.width - 40,
                      decoration: BoxDecoration(
                          color: Colors.white, borderRadius: 10.borderRadius));
                },
                tag: callInfo.id.toString(),
                keepSingle: true);
          }
        },
        receiveWarningHandle: (info) {
          SmartDialog.dismiss(tag: info.id.toString());
          dialogTag.remove(info.id.toString());
        },
        receiveMapInfo: (map) {});
  }

  void receiveSosMsg() {
    FlutterBackgroundService().on("serviceStart").listen((event) {
      // SosWarningService.instance.sendUrlMsg(HttpApi.baseUrl,RequestUrlUtils.branchId,accountName: UserManager.userName??"admin111");
    });

    FlutterBackgroundService().on("sendHandle").listen((event) {
      CallWarningData callInfo = CallWarningData.fromMap(event!['callInfo']);
      SmartDialog.dismiss(tag: callInfo.id.toString());
      dialogTag.remove(callInfo.id.toString());
    });
    FlutterBackgroundService().on("sosMsg").listen((event) async {
      CallWarningData callInfo = CallWarningData.fromMap(event!['callInfo']);
      if (GlobalConfigs.showSosInStatusBar) {
        NotifycationUtils.instance.showSosMessage(callInfo.msg);
      }
      if (isInWarning) {
        return;
      }
      if (dialogTag.isNotEmpty) {
        for (var item in dialogTag) {
          await SmartDialog.dismiss(tag: item);
        }
      }

      dialogTag.add(callInfo.id.toStringOrNull() ?? "");
      SmartDialog.show(
          builder: (_context) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  height: 16,
                ),
                CommonText('报警提醒'),
                SizedBox(
                  height: 16,
                ),
                CommonText(callInfo.msg, textAlign: TextAlign.center)
                    .addToContainer(
                        padding: EdgeInsets.symmetric(horizontal: 12)),
                SizedBox(
                  height: 16,
                ),
                TextButton(
                    onPressed: () {
                      SmartDialog.dismiss(tag: callInfo.id.toString());
                      NavigatorUtils.push(
                          context, HomeRouter.medicalPolicyPage);
                    },
                    child: CommonText('前往处理'))
              ],
            ).addToContainer(
                width: MediaQuery.of(_context).size.width - 40,
                decoration: BoxDecoration(
                    color: Colors.white, borderRadius: 10.borderRadius));
          },
          tag: callInfo.id.toString(),
          keepSingle: true);
    });
  }

  Future<void> _submitPatrolByNfc(String code) async {
    showLoadingDialog(msg: "正在提交...");
    try {
      await patrolModel.submitPatrolDirect(code);
      hideDialog();
      showToast("打卡成功");
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  Future<void> getSysInfo() async {
    try {
      var data = await sysModel.getSysInfo("defaultNormal", "patrolDomain");
      GlobalConfigs.nfcSubmitDirect = data?.paramValue == "1";
    } catch (e) {
      print(e);
    }
  }

  var permissions = [
    Permission.camera,
    Permission.storage,
    // Permission.microphone,
    Permission.location,
    Permission.locationWhenInUse,
    Permission.locationAlways,
    Permission.bluetoothScan,
    Permission.bluetoothConnect,
    Permission.bluetooth,
  ];

  Future<void> requestPermission() async {
    await Permission.bluetoothScan.request();
    await Permission.location.request();
    await Permission.bluetoothConnect.request();
  }

  Future<void> checkWarningSetting() async {
    if (!GlobalConfigs.hasSetWaring) {
      ///前去设置
      var data = await Go().push(SetWarningInfoPage());
      if (data != null) {
        _setSosService();
      }
    }
  }
}

class HomeIconData {
  String funName;
  String funImage;

  HomeIconData(this.funImage, this.funName);
}
